import java.util.HashSet;

import efg.library.IF.BookDAO;
import efg.library.IF.CustomerDAO;
import efg.library.IF.LibraryManagerIF;

import javax.naming.InitialContext;
import org.jboss.security.client.SecurityClient;
import org.jboss.security.client.SecurityClientFactory;

public class Main
{
	public static void main(String[] args) throws Exception
	{    
		InitialContext ctx = new InitialContext();
		LibraryManagerIF manager = (LibraryManagerIF)ctx.lookup("LibraryManagerBean/remote");     
		System.out.println("librarymanager="+manager);

		SecurityClient securityClient = SecurityClientFactory.getSecurityClient();

		securityClient.setSimple("henk", "geheim");
		securityClient.login();
		
		try {
			manager.newCustomer("Eric");
			manager.newCustomer("Fred");
			manager.newCustomer("Henk");
			manager.newCustomer("John");
			manager.newBook("JavaServer Faces in Action");
			manager.newBook("jQuery in Action");
			manager.newBook("Pro J2EE 1.4 From Professional to Expert");
			manager.newBook("The Java Programming Language, Fourth Edition");
			System.out.println("Testdata succesvol toegevoegd!\n");
		} catch(Exception e) {
			System.out.println("Testdata al in database.\n");
		}
		
		printBooks(manager);         
		printCustomers(manager);
		manager.addCredits("Eric", 1);
		printCustomers(manager);
		securityClient.logout();
		securityClient.setSimple("john", "geheim");
		securityClient.login();
		printBooks(manager); 
		manager.newBook("aapje");
		printBooks(manager);   

		printCustomers(manager); 
		manager.newCustomer("aapje");
		printCustomers(manager);
		manager.removeCustomer("aapje");    
		printCustomers(manager);
		securityClient.logout();   

		securityClient.setSimple("fred", "geheim");
		securityClient.login();
		printCustomers(manager);
		manager.lend("aapje", "Eric");
		printCustomers(manager);
		securityClient.logout();

		securityClient.setSimple("john", "geheim");
		securityClient.login();
		printBooks(manager);
		manager.removeBook("aapje");
		manager.lend("aapje", "Eric");
		printBooks(manager); 
		securityClient.logout();  
	}

	private static void printBooks(LibraryManagerIF manager)
	{
		HashSet<BookDAO> books = manager.allBooks();
		for (BookDAO book : books)
		{
			System.out.println(book.getTitle()); 
		}     
		System.out.println("----------------------------------------------");
	}

	private static void printCustomers(LibraryManagerIF manager)
	{
		HashSet<CustomerDAO> customers = manager.allCustomers();
		for (CustomerDAO customer : customers)
		{
			System.out.print(customer.getName()+", "+customer.getCredits());
			HashSet<String> books = customer.getBooks();
			for (String title : books)
			{
				System.out.print(", "+title); 
			}
			System.out.println();
		} 
		System.out.println("----------------------------------------------");   
	}
}